package com.artifex.mupdf.viewer

import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.text.format.DateUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.artifex.mupdf.viewer.databinding.ActivityTimerSettingsBinding
import java.nio.charset.StandardCharsets
import java.util.Base64


class TimerSettingsActivity : AppCompatActivity() {

    private var countdownTimer: CountDownTimer? = null
    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var binding: ActivityTimerSettingsBinding

    override fun onCreate(savedInstanceState: Bundle?) {

        if(intent == null || intent.data == null) {
            Toast.makeText(this, "No data", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = Base64.getUrlEncoder().encodeToString(intent.data.toString().toByteArray(StandardCharsets.UTF_8));
            sharedPreferences = getSharedPreferences(name, MODE_PRIVATE)
        } else {
            Toast.makeText(this, "Low version code", Toast.LENGTH_SHORT).show()
            finish()
            return
        }


        ViewCompat.setOnApplyWindowInsetsListener(
            window.decorView
        ) { v: View?, insets: WindowInsetsCompat? ->
            val systemBars: Insets = insets!!.getInsets(WindowInsetsCompat.Type.systemBars())
            v!!.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        super.onCreate(savedInstanceState)
        binding = ActivityTimerSettingsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Check if a timer is already active
        if (sharedPreferences.contains("timer_end_time")) {
            startCountdown()
        }

        binding.btnStartTimer.setOnClickListener {
            val minutesText = binding.etTimerMinutes.text.toString()
            if (minutesText.isNotEmpty()) {
                val minutes = minutesText.toLong()
                if (minutes > 0) {
                    val durationMillis = minutes * 1000
                    val endTime = System.currentTimeMillis() + durationMillis
                    // Save the timer duration in SharedPreferences
                    sharedPreferences.edit {
                        putLong("timer_end_time", endTime)
                        apply()
                    }
                    Log.d("TimerSettings", "timer saved:$endTime")

                    startCountdown()
                } else {
                    Toast.makeText(this, "Please enter a valid number of minutes.", Toast.LENGTH_SHORT).show()
                }
            } else {
                Toast.makeText(this, "Please enter the duration.", Toast.LENGTH_SHORT).show()
            }
        }
        binding.toolbar.setNavigationOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }


    }

    private fun startCountdown() {
        val endTime = sharedPreferences.getLong("timer_end_time", 0)
        if(System.currentTimeMillis() > endTime) {
            Toast.makeText(this, "Time's up!", Toast.LENGTH_SHORT).show()
            sharedPreferences.edit { remove("timer_end_time")
                remove("timer_end_time")
                apply()
            }
            return;
        }
        val durationMillis = endTime - System.currentTimeMillis()

        // Clear any existing timer
        countdownTimer?.cancel()

        // Hide the input field and button once timer starts
        binding.etTimerMinutes.isEnabled = false
        binding.btnStartTimer.isEnabled = false
        binding.btnStartTimer.text = getString(R.string.timer_active)


        countdownTimer = object : CountDownTimer(durationMillis, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val remainingTime = DateUtils.formatElapsedTime(millisUntilFinished / 1000)
                binding.tvTimerStatus.text = "Time remaining: $remainingTime"
            }

            override fun onFinish() {
                binding.tvTimerStatus.text = getString(R.string.time_s_up)
                // The app will be finished by the onStop() logic
                runOnUiThread { finishAffinity() }
            }
        }.start()
    }

//    override fun onStop() {
//        super.onStop()
//        // When the activity is no longer visible, finish the app
//        finishAffinity()
//    }

    override fun onDestroy() {
        super.onDestroy()
        // Always cancel the timer to prevent memory leaks
        countdownTimer?.cancel()
    }
}